package com.netease.nie.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.netease.nie.SpringBootApplicationContextUtils;
import com.netease.nie.base.cache.redis.Redis;
import com.netease.nie.base.exceptions.UnexpectedException;
import com.netease.nie.constants.CachePrefixConstants;
import com.netease.nie.dto.UserLoginDto;
import com.netease.nie.service.UserService;
import com.netease.nie.utils.UserLoginUtils;

/**
 * 
 * @author wwbn3695
 * @createDate June 30th,2016
 *
 */
public class UserInterceptor implements HandlerInterceptor {
	
	private static Logger logger = Logger.getLogger(UserInterceptor.class);
	
	private static final String USER_TOKEN_PREFIX = CachePrefixConstants.UserPrefix.USER_TOKEN_PREFIX;
	
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		//获取用户登录信息
		logger.warn("url: " + request.getRequestURL() + "?" + request.getQueryString());
		UserLoginDto userLoginDto = UserLoginUtils.getUserLoginDto(request);
		if (userLoginDto != null) {
			logger.warn("userLoginDto: " + userLoginDto.toString());
			String userToken = UserLoginUtils.generateUserToken(userLoginDto);
			Long userId = queryUserInfoId(userToken);
			logger.warn("userId: " + userId);
			if (userId == null) {
				userId = resetUserToken(userLoginDto, userToken);
				if (userId == null)
					UserLoginUtils.deleteNeteaseMobileCookie(request, response);
			}
			request.setAttribute("userId", userId);
		} else 
			request.setAttribute("userId", null);
		return true;
	}
	
	
	private Long queryUserInfoId(String userToken) {
		if (StringUtils.isBlank(userToken))
			return null;
		Redis redis = SpringBootApplicationContextUtils.getBean(Redis.class);
		String userTokenKey = USER_TOKEN_PREFIX + userToken;
		String userInfoId = redis.get(userTokenKey);
		if (StringUtils.isBlank(userInfoId)) {
			return null;
		}
		return Long.valueOf(userInfoId);
	}
	
	private Long resetUserToken(UserLoginDto userLoginDto, String userToken) {
		if (StringUtils.isBlank(userLoginDto.getSsn()))
			throw new UnexpectedException("cookie解析错误");
		
		UserService userService = SpringBootApplicationContextUtils.getBean(UserService.class);
		Long userId = userService.queryUserIdBySsn(userLoginDto.getSsn());
		if (userId != null) {
			Redis redis = SpringBootApplicationContextUtils.getBean(Redis.class);		
			String userTokenKey = USER_TOKEN_PREFIX + userToken;
			redis.setex(userTokenKey, String.valueOf(userId), 604800);
		}
		return userId;
	}

}
